package com.jpemartin.jgt;

import java.awt.Rectangle;
import java.awt.event.KeyEvent;


/**
 * Moves in the direction of the arrow you push;
 * if you hold it down you'll move faster
 * if you touch nothing, you slow to a stop,
 * 
 * @author jpmartin
 */
public class MoveKeyboardAccel implements MoveControl {
   
   // bounds
   int _minX, _minY, _maxX, _maxY;
   // direction
   private int _dx, _dy;
   //object that keeps track of the keyboard status
   private KeyboardStatus _kbd;
   // how fast you accelerate when you hold on to the direction key
   private static final int _accel=1;
   // how quickly the movement slows when you touch nothing
   private static final int _decel=3;
   
   
   public MoveKeyboardAccel(KeyboardStatus k, int minX,int minY,int maxX,int maxY) {
      _minX = minX;
      _minY = minY;
      _maxX = maxX;
      _maxY = maxY;   
      _kbd = k;
   }
   
   public void move(Rectangle me) {
      
      // no keyboard? do nothing
      if (null==_kbd) return;
      
//    the four directions
      boolean u, d, l, r;
      
      d = _kbd.key[KeyEvent.VK_DOWN];
      u = _kbd.key[KeyEvent.VK_UP];
      r = _kbd.key[KeyEvent.VK_RIGHT];
      l = _kbd.key[KeyEvent.VK_LEFT];
      
      // holding left and right at the same time is the same as holding neither
      int dx = (r?_accel:0) - (l?_accel:0);
      int dy = (d?_accel:0) - (u?_accel:0);
      
      accel(dx,dy);
      
      if (dy==0) {
         // slow down to zero
         if (_dy > _decel)
            _dy-=_decel;
         else if (_dy < -_decel) _dy+=_decel;
         else _dy=0;
      }
      if (dx==0) {
         // slow down to zero
         if (_dx > _decel)
            _dx-=_decel;
         else if (_dx < -_decel) _dx+=_decel;
         else _dx=0;
      }
      
      me.x += _dx;
      me.y += _dy;
      
      if (me.x<_minX) me.x=_minX;
      else if (me.x>_maxX-me.width) me.x=_maxX-me.width;
      if (me.y<_minY) me.y=_minY;
      else if (me.y>_maxY-me.height) me.y=_maxY-me.height;        
   }
   
   
   private final void accel(int dx, int dy) {
      final int max = 10;
      _dx += dx;
      if (_dx < -max) _dx = -max;
      if (_dx > max) _dx = max;
      _dy += dy;
      if (_dy < -max) _dy = -max;
      if (_dy > max) _dy = max;
      
   }
   
}
